/*
 * @Author: 姚杰鸿 adolphus520@163.com
 * @Date: 2024-07-19 11:11:21
 * @LastEditors: 姚杰鸿
 * @LastEditTime: 2024-07-19 11:18:40
 * @Description: file content
 */
import type Node from "element-plus/es/components/tree/src/model/node";
import type { TreeData } from "@/lib/vars";
import type { TreeNodeData } from "element-plus/es/components/tree/src/tree.type";

export const CalulerTreeOrdernn = (
  node1: Node,
  node2: Node,
  local: string,
  data: TreeData[] | null | undefined,
  chk1: (d: TreeNodeData) => boolean
): TreeNodeData | undefined => {
  const data1 = node1.data;
  const data2 = node2.data;
  if (local === "inner") {
    if (chk1(data2)) {
      return undefined;
    }
    data1.pcode = data2.code;
    let maxOrderNm = 0;
    for (let i = 0; i < data2.children.length; i++) {
      if (data2.children[i].code != data1.code) {
        maxOrderNm =
          maxOrderNm < data2.children[i].ordernn
            ? data2.children[i].ordernn
            : maxOrderNm;
      }
      console.log(data2.children[i].name, data2.children[i].ordernn);
    }
    data1.ordernn = maxOrderNm + 1;
  } else {
    data1.pcode = data2.pcode;
    const datas: TreeData[] = new Array<TreeData>();
    const fdMenuTree = (item: TreeData) => {
      if (item.pcode === data2.pcode) {
        datas.push(item);
      } else if (item.children && 0 < item.children.length) {
        item.children.forEach(fdMenuTree);
      }
    };
    data?.forEach(fdMenuTree);
    for (let i = 0; i < datas.length; i++) {
      if (datas[i].code === data2.code) {
        if (i > 0 && local === "before" && i > 1) {
          data1.ordernn = (datas[i - 2].ordernn + data2.ordernn) / 2;
        } else if (i > 0 && local === "before") {
          data1.ordernn = data2.ordernn + 1;
        } else if (
          i + 1 < datas.length &&
          local === "after" &&
          i + 2 < datas.length
        ) {
          data1.ordernn = (data2.ordernn + datas[i + 2].ordernn) / 2;
        } else if (i + 1 < datas.length && datas[i + 1].code === data1.code) {
          data1.ordernn = (data2.ordernn + 0) / 2;
        }
      }
    }
  }
  return data1;
};
